About 852 letters

About 4 minutes

#Python's anonymous functions

Anonymous functions let you quickly create simple functions without defining a full function using the def keyword. In Python, anonymous functions are created with the lambda keyword:

lambda parameter_list : return_value

For example:

names: list[str] = ['Tuffy', 'Spike', 'Tom', 'Jerry']
names.sort(key=lambda x: len(x))  # Sort by length
print(names)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#First-Class Functions

In Python, functions are first-class values, meaning you can assign them directly to variables:

# Define a function
def func(x: str):
    return len(x)

# Assign function to a variable
variable = func

# Call function through the variable
print(variable('hello'))

# Simplify with lambda
variable = lambda x: len(x)

# Call function through the variable
print(variable('world'))

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025